package com.home.cca.network;

import com.google.gson.Gson;
import com.home.cca.model.Order;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Request;

public class DeliverOrdersRequest {

    private static final String URL = ApiClient.getBaseUrl() + "/SupplierManager/PSOrderMgr/DeliverGoods";

    /**
     * 订单发货
     */
    public static Order deliver(Order order) throws IOException {
        FormBody body = new FormBody.Builder()
                .add("buyOrderId", String.valueOf(order.getId()))
                .build();

        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", ApiClient.getCookie())
                .header("Origin", ApiClient.getBaseUrl())
                .header("Referer", ApiClient.getBaseUrl())
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("docktoken", "")
                .build();

        String execute = ApiClient.execute(request);
        String[] split = execute.split("\n");
        for (String str : split) {
            String trim = str.trim();
            if (trim.startsWith("var model") && trim.endsWith(";")) {
                String arr = trim.substring(12, trim.length() - 2);
                if (arr.isEmpty()) {
                    throw new IOException("查询发货信息异常");
                }
                Order o = new Gson().fromJson(arr, Order.class);
                o.setId(order.getId());
                return o;
            }
        }
        throw new IOException("查询发货信息异常");
    }
}